import json
import logging

from django.shortcuts import render, redirect, HttpResponse
from django.db.models import Q

from mac import models
from mac.forms import department_forms, user_forms, product_forms
from mac.utils import page
from mac.utils import encrypt

logger = logging.getLogger(__name__)


def user_list(request):
    '''
    查看所有用户
    :param request:
    :return:
    '''
    if request.method == 'POST':
        search = request.POST.get('search')
        users_query = models.UserInfo.objects.filter(Q(depart_id__department_name__icontains=search)
                                                    | Q(role__icontains=search)
                                                    | Q(phone__icontains=search)
                                                    | Q(fullname__icontains=search)
                                                    | Q(username__icontains=search))
    else:
        users_query = models.UserInfo.objects.all()
    user_count = users_query.count()
    pages = request.GET.get('page')
    user_page_size = request.GET.get('user_page_size')
    if not user_page_size:
        user_page_size = request.session.get('user_page_size', 20)
    else:
        request.session['user_page_size'] = request.GET.get('user_page_size')

    users_obj = page.PageInfo(current_page=pages,
                              all_count=user_count,
                              url='/user_list/',
                              per_page=user_page_size)
    users_page_obj = users_query[users_obj.start():users_obj.end()]
    return render(request, 'user_list.html', {"users_obj": users_page_obj,
                                              'pages': users_obj.pager(),
                                              'user_page_size': user_page_size,
                                              'user_count': user_count
                                              })


def user_add(request):
    '''
    新增用户
    :param request:
    :return:
    '''
    if request.method == 'GET':
        users_form = user_forms.UserAddForm()
        return render(request, 'user_add.html', {'users_form': users_form})
    users_form = user_forms.UserAddForm(request.POST)
    if users_form.is_valid():
        try:
            users_form.save()
        except UnicodeError as e:
            logger.error(e)
            return render(request, '500.html')
        return redirect('user_list')
    return render(request, 'user_add.html', {'users_form': users_form})


def user_edit(request, uid):
    '''
    修改用户
    :param request:
    :param uid:
    :return:
    '''
    user_obj = models.UserInfo.objects.filter(id=uid).first()
    if request.method == 'GET':
        users_form = user_forms.UserEditForm(instance=user_obj)
        return render(request, 'user_add.html', {'users_form': users_form, "uid": uid})
    users_form = user_forms.UserEditForm(request.POST, instance=user_obj)
    if users_form.is_valid():
        try:
            users_form.save()
        except UnicodeError as e:
            logger.error(e)
            return render(request, '500.html')
        return redirect('user_list')


def user_delete(request, uid):
    '''
    删除用户
    :param request:
    :param uid:
    :return:
    '''
    models.UserInfo.objects.filter(id=uid).delete()
    return redirect('user_list')


def user_password_edit(request):
    '''
    修改密码
    :param request:
    :return:
    '''
    if request.method == 'GET':
        return render(request, 'user_password_edit.html')
    oldpwd = encrypt.md5(request.POST.get('oldpwd'))
    newpwd = request.POST.get('newpwd')
    newpwd2 = request.POST.get('newpwd2')
    user_obj = models.UserInfo.objects.filter(id=request.mac.user.id).first()
    if oldpwd == user_obj.password:
        if newpwd == newpwd2:
            models.UserInfo.objects.filter(id=request.mac.user.id).update(password=encrypt.md5(newpwd))
            return redirect('mac_home')
        return render(request, 'user_password_edit.html', {'error': '两次密码不一致', 'oldpwd': oldpwd})
    return render(request, 'user_password_edit.html', {'error': '原来密码错误'})


def department_list(request):
    '''
    部门列表
    :param request:
    :return:
    '''
    departments_query = models.Department.objects.all()
    pages = request.GET.get('page')
    department_obj = page.PageInfo(current_page=pages, all_count=departments_query.count(), url='/department_list/')
    department_page_obj = departments_query[department_obj.start():department_obj.end()]
    return render(request, 'department_list.html', {'department_obj': department_page_obj, 'pages': department_obj.pager()})


def department_add(request):
    '''
    新增部门
    :param request:
    :return:
    '''
    if request.method == 'GET':
        departments_form = department_forms.DepartmentAddForm()
        return render(request, 'department_add.html', {'departments_form': departments_form})
    departments_form = department_forms.DepartmentAddForm(request.POST)

    if departments_form.is_valid():
        try:
            departments_form.save()
        except UnicodeError as e:
            logger.error(e)
            return render(request, '500.html')
        return redirect('department_list')

    return render(request, 'department_add.html', {'departments_form': departments_form})


def department_edit(request, did):
    '''
    修改部门
    :param request:
    :param did:
    :return:
    '''
    department_obj = models.Department.objects.filter(id=did).first()
    if request.method == 'GET':
        departments_form = department_forms.DepartmentEditForm(instance=department_obj)
        return render(request, 'department_add.html', {'departments_form': departments_form, "did": did})
    departments_form = department_forms.DepartmentEditForm(request.POST, instance=department_obj)
    if departments_form.is_valid():
        try:
            departments_form.save()
        except UnicodeError as e:
            logger.error(e)
            return render(request, '500.html')
        return redirect('department_list')


def department_delete(request, did):
    '''
    删除部门
    :param request:
    :param did:
    :return:
    '''
    models.Department.objects.filter(id=did).delete()
    return redirect('department_list')


def product_list(request):
    '''
    产品列表
    :param request:
    :return:
    '''
    if request.method == 'POST':
        search = request.POST.get('search')
        products_query = models.Product.objects.filter(Q(name__icontains=search)
                                                    | Q(model__icontains=search)
                                                    | Q(cpu__icontains=search)
                                                    | Q(board__icontains=search)
                                                    | Q(company__icontains=search)
                                                    | Q(flash__icontains=search)
                                                    | Q(memory__icontains=search))
    else:
        products_query = models.Product.objects.all()
    product_count = products_query.count()
    pages = request.GET.get('page')
    product_page_size = request.GET.get('product_page_size')
    if not product_page_size:
        product_page_size = request.session.get('product_page_size', 20)
    else:
        request.session['product_page_size'] = request.GET.get('product_page_size')
    product_obj = page.PageInfo(current_page=pages,
                                all_count=product_count,
                                url='/product_list/',
                                per_page=product_page_size)
    product_page_obj = products_query[product_obj.start():product_obj.end()]
    return render(request, 'product_list.html', {"product_obj": product_page_obj,
                                                 'pages': product_obj.pager(),
                                                 'product_page_size': product_page_size,
                                                 'product_count': product_count
                                                 })


def product_add(request):
    '''
    新增产品
    :param request:
    :return:
    '''
    if request.method == 'GET':
        products_form = product_forms.ProductAddForm()
        return render(request, 'product_add.html', {'products_form': products_form})
    products_form = product_forms.ProductAddForm(request.POST)
    if products_form.is_valid():
        try:
            products_form.save()
        except UnicodeError as e:
            logger.error(e)
            return render(request, '500.html')
        return redirect('product_list')
    return render(request, 'product_add.html', {'products_form': products_form})


def product_edit(request, pid):
    '''
    修改产品
    :param request:
    :param pid:
    :return:
    '''
    product_form = models.Product.objects.filter(id=pid).first()
    if request.method == 'GET':
        products_form = product_forms.ProductEditForm(instance=product_form)
        return render(request, 'product_add.html', {'products_form': products_form, "pid": pid})
    products_form = product_forms.ProductEditForm(data=request.POST, instance=product_form)
    if products_form.is_valid():
        try:
            products_form.save()
        except UnicodeError as e:
            logger.error(e)
            return render(request, '500.html')
        return redirect('product_list')
    return render(request, 'product_add.html', {'products_form': products_form, "pid": pid})


def product_delete(request, pid):
    '''
    删除产品
    :param request:
    :param pid:
    :return:
    '''
    models.Product.objects.filter(id=pid).delete()
    return redirect('product_list')


def bulk_delete(request):
    '''
    批量删除
    :param request:
    :return:
    '''
    data = {'status': True}
    id_list = request.POST.getlist('mac_details_id_list[]')
    if not id_list:
        data['status'] = False
        return HttpResponse(json.dumps(data))
    if request.POST.get('url') == '/download_details/':
        models.MacGenerateRecode.objects.filter(id__in=id_list).delete()
        return HttpResponse(json.dumps(data))
    if request.POST.get('url') == '/product_list/':
        models.Product.objects.filter(id__in=id_list).delete()
        return HttpResponse(json.dumps(data))
    if request.POST.get('url') == '/user_list/':
        models.UserInfo.objects.filter(id__in=id_list).delete()
        return HttpResponse(json.dumps(data))
    if request.POST.get('url') == '/query_delivery_order/':
        models.Notice.objects.filter(id__in=id_list).delete()
        return HttpResponse(json.dumps(data))
    if request.POST.get('url') == '/jurisdiction_list/':
        models.Jurisdiction.objects.filter(id__in=id_list).delete()
        return HttpResponse(json.dumps(data))
